package com.example.view;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.app.MyApplication;
import com.example.netity.Tminfo;
import com.example.netity.order;
import com.example.tool.BaseActivity;
import com.example.tool.DateTimePickDialogUtil;
import com.example.tool.MyAdapter;
import com.example.tool.MylisAdapter;
import com.example.tool.Utils;
import com.example.tool.XListView;
import com.example.tool.XListView.IXListViewListener;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class SecondActivity extends BaseActivity implements OnClickListener{
	private XListView xlv;
	private ListView lv;
	MylisAdapter adapter=null;
	MyAdapter adapter1=null;
	String urll= MyApplication.SERVERPATH + "/Y502/getTminfo";
	private String logourl=MyApplication.SERVERPATH+"/Y502/Pad2getorder";
	int num=0;
	 RequestQueue mQueue =null;
	JsonObjectRequest mJsonObjectRequest=null;
	ArrayList<Tminfo> list=new ArrayList<Tminfo>();
	public  ArrayList<order> list1=new ArrayList<order>();
	String uu="",sn="";
	String po="";
	String riqi="";
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	private ImageView image;
	private TextView rq;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,      
                WindowManager.LayoutParams. FLAG_FULLSCREEN); 
		setContentView(R.layout.activity_second);
		sn=getIntent().getStringExtra("sn");
		long thistime = MyApplication.xtime * 1000 + System.currentTimeMillis();
		riqi=df.format(new Date(thistime));
		mQueue=MyApplication.getRequestQueue();
		getdata2();
		setView();
	}
	private void getdata2() {		
		boolean isConnected = Utils.toastIsNetworkConnected(this);
		if (isConnected) {				
		 uu=logourl+"?sn="+sn+"&&riqi="+riqi;
		//RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
         mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST,uu,
        		 null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {            	
            	parseData2( response);
            }

			
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {     	  	
    	showToast(getString(R.string.network_error_try_again));	
    }
   }
  );
        mQueue.add(mJsonObjectRequest);	
		}
		else
		{
			showToast(getString(R.string.network_error_try_again));
			return;
		}	
	}
	protected void parseData2(final JSONObject response) {
		runOnUiThread(new Runnable() {
			public void run() {											
					String re = null;
					try {
						re = response.getString("result");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(re.equals("yes"))
					{
						list1.clear();
				         JSONArray array = response.optJSONArray("data");
				        if (array != null)
				        {
					      for (int i = 0; i < array.length(); i++) 
					      {
					    	  JSONObject obj = array.optJSONObject(i);
					    	  order o=new order();
					    	  o.setPo(obj.optString("po"));
					    	  o.setNum(obj.optString("num"));
					    	  o.setWnum(obj.optString("wnum"));
					    	  list1.add(o);					    	 				    	 					    			   						   
					      }						      
				        }
				        adapter.notifyDataSetChanged(); 
				        list.clear();
				        adapter1.notifyDataSetChanged();	
				   } 				
				}							
		});
		
	}
	@Override
	public void onClick(View v) {
		 switch(v.getId())
		 {		
		 case R.id.second_riqi:
			 if(!l)
			 {
				 DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(  
                     SecondActivity.this, riqi);  
             dateTimePicKDialog.dateTimePicKDialog(rq); 
			 }
			                     			 
			 break;		
		 }
		
	}
	boolean l=false;
	private void setView() {
		xlv=(XListView)findViewById(R.id.second_xlv);
		lv=(ListView)findViewById(R.id.second_lv1);
		adapter=new MylisAdapter(this,list1);
		image=(ImageView)findViewById(R.id.second_return);
		image.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				l=true;
				MyApplication.index=-2;				
				SecondActivity.this.finish();			
			}
		});
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				MyApplication.index2=MyApplication.index;
				MyApplication.index=position;				
				adapter.notifyDataSetChanged();
			    po=list1.get(position).getPo();
				num=0;
				uu=urll+"?po="+po+"&&num="+num+"&&riqi="+riqi;
				getData(uu);				
			}
		});
		adapter1 = new MyAdapter(this, list);
		xlv.setAdapter(adapter1);
		xlv.setPullLoadEnable(true);
		xlv.setPullRefreshEnable(true);
		xlv.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				xlv.stopRefresh();
				if(num>0)
					num--;
				 uu=urll+"?po="+po+"&&num="+num+"&&riqi="+riqi;
				getData(uu);
			}

			@Override
			public void onLoadMore() {
				if(list.size()>=20)
				{
					num++;
				    uu=urll+"?po="+po+"&&num="+num+"&&riqi="+riqi;
				   getData(uu);
				}				
			}
		});
		xlv.showFooter(false);			
		rq=(TextView)findViewById(R.id.second_riqi);
		rq.setText(riqi);
		rq.setOnClickListener(this);
		rq.addTextChangedListener(new TextWatcher(){

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
	         String srq=rq.getText().toString();
	         if(!riqi.equals(srq))
	         {
	        	 riqi=srq;
	        	 getdata2();
	         }
			}

			@Override
			public void afterTextChanged(Editable s) {
				
			}});
	}
	private void getData(String uu) {
		boolean isConnected = Utils.toastIsNetworkConnected(this);
		if (isConnected) {				
		//RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
         mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST,uu,
        		 null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {            	
            	parseData( response);
            }			
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {     	  	
    	showToast(getString(R.string.network_error_try_again));	
    }
   }
  );
        mQueue.add(mJsonObjectRequest);	
		}
		else
		{
			showToast(getString(R.string.network_error_try_again));
			return;
		}	
	}
	public void parseData(final JSONObject response) {
		
		runOnUiThread(new Runnable() {
			public void run() {															
					String re = null;
					try {
						re = response.getString("result");
					} catch (JSONException e) {					
						e.printStackTrace();
					}
					if(re.equals("yes"))
					{
				         JSONArray array = response.optJSONArray("data");			         
				        if (array != null)
				        {
				        	list.clear();
					      for (int i = 0; i < array.length(); i++) 
					      {
					    	  JSONObject obj = array.optJSONObject(i);
							   Tminfo b = new Tminfo();
							    b.setId(num*20+i+1+"");
							    b.setShijian(obj.optString("shijian"));
							    b.setTm(obj.optString("tm"));							    
							   list.add(b);
					      }	
					      adapter1.notifyDataSetChanged();	
				        }	
				        
				   } 				
				}							
		});				
	}
}
